package db

import (
	"fmt"
	"project/PersonalBlog/model"
	"strconv"
	"strings"
	"time"
)

//InsertCategory ..
func InsertCategory(category *model.Category) (categoryid int64, err error) {
	updatatime := time.Now()
	res, err := Stmt[StmtInsertCategory].Exec(category.CategoryName, category.CategoryNo, updatatime)
	if err != nil {
		return 0, err
	}
	id, err := res.LastInsertId()
	return id, err
}

//GetCategory 获取单个文章分类
func GetCategory(categoryid int64) *model.Category {
	category := &model.Category{
		CategoryID: categoryid,
	}
	err := Stmt[StmtGetCategory].QueryRow(categoryid).Scan(&category.CategoryName, &category.CategoryNo, &category.CreateTime, &category.UpdateTime)
	if err != nil {
		return nil
	}
	return category
}

//GetCategorys 获取多个分类
func GetCategorys(categoryid []int64) (categoryList []*model.Category, err error) {
	sqlstr := ""
	for _, v := range categoryid {
		sqlstr += strconv.FormatInt(v, 10)
		sqlstr += ","
	}
	sqlstr = strings.Trim(sqlstr, ",")
	rows, err := Stmt[StmtGetCategorys].Query(sqlstr)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		category := &model.Category{}
		err := rows.Scan(&category.CategoryID, &category.CategoryName, &category.CategoryNo, &category.CreateTime, &category.UpdateTime)
		if err != nil {
			fmt.Println(err.Error())
			continue
		}
		categoryList = append(categoryList, category)
	}
	return
}

//GetAllCategor ..获取所有分类
func GetAllCategor() (categoryList []*model.Category) {
	rows, err := Stmt[StmtGetAllCategory].Query()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer rows.Close()
	for rows.Next() {
		category := &model.Category{}
		err := rows.Scan(&category.CategoryID, &category.CategoryName, &category.CategoryNo, &category.CreateTime, &category.UpdateTime)
		if err != nil {
			fmt.Println(err.Error())
			continue
		}
		categoryList = append(categoryList, category)
	}
	if len(categoryList) == 0 {
		return nil
	}
	return
}
